(function($) {

//var plugin = {
//	//Nom de la classe à instancier /!\ CE NOM DOIT ETRE UNIQUE ET IDENTIQUE AU NOM JQUERY /!\
//	name: 'MapsPlugin'
//};

// Constructeur
var MapsPlugin = function(options){ // rajouter element
	//console.log(this);
	if(arguments.length) {
		this._init( options );// rajouter element
	} else 
		console.log('Aucun paramètre reçu pour MapsPlugin');
};

MapsPlugin.prototype = {
	name: 'MapsPlugin',
	
	defaults: {
		data: {
		}
	},
	
	_init: function(options){// rajouter element
		var t = this;
		
		// Public
		t.$element = $(options.element);
		t.defaults = $.extend(true, {}, t.defaults, options);
		
		t.idEvent = t.defaults.idEvent;
		
		if(t.idEvent == 0){
			t.$element.html('<div class="alert">L\'événement doit être enregistré pour ajouter un lieu');
		} else {
			t.$element.html(t.defaults.content);
			
			t.google = $.fn.google;
	
			t.google.maps.visualRefresh = true;
			
			t.address = $('#em-plugin-maps-form input[type=text]').val();	
			
			t.initialize();
	
			t.google.maps.event.addDomListener(window, 'load', t.refreshMap);
		}
	},
	
	initialize: function() {
		var t = this;
		
		t.refreshMap();		
		
		$('#em-plugin-maps-form').on('maps-refresh', function(e){
			t.refreshMap();
		});
		
		$('#em-plugin-maps-form').on('submit', function(e){
			e.preventDefault();
			
			t.address = $(this).find('input[type=text]').val();
			
			var dataSend = {address : t.address};
			
			var urlUpdate = t.defaults.options.urlBase + 
			t.defaults.options.urlPattern
				.replace(/idEvent/, t.idEvent)
				.replace(/action/, t.defaults.options.urlUpdateAction);
		
			$.ajax({
	    		type: 'POST',
	    		url: urlUpdate,
			  	data: dataSend,
			    dataType: "json"
	    	}).done(function(jsonResult) {
	    		if(jsonResult && typeof jsonResult.result != 'undefined'){
	        		if(jsonResult.result == 200){
	        			t.refreshMap();
	        			
	        			if(typeof callback == 'function'){
	        				callback();
	        			} else {
	        				$.pnotify({
		                        title: "Terminé !",
		                        text: jsonResult.msg,
		                        type: "success"
		                    });
	        			}
	        		} else if(jsonResult.result == 500){
	        			$.pnotify({
	                        title: "Erreur !",
	                        text: jsonResult.msg,
	                        type: "error"
	                    });
	        		}
	    		} else {
	    			alert('La réponse du serveur est incorrecte');
	        	}
	    	}).fail(function(jqXHR, textStatus, errorThrown) {
	    		alert('Une erreur est survenue ('+errorThrown+')');
	    	}).always(function(jqXHR, textStatus, errorThrown) {});	
		});
	},
	
	refreshMap: function(){
		var map;
		var geocoder;
		
		var t = this;
			google = t.google;
		
		geocoder = new t.google.maps.Geocoder();
		
		geocoder.geocode( { 'address': t.address}, function(results, status) {
			if (status == t.google.maps.GeocoderStatus.OK) {
				map.setCenter(results[0].geometry.location);
				var marker = new t.google.maps.Marker({
					map: map,
					position: results[0].geometry.location
				});
				var contentString = t.address;
			
				var infowindow = new t.google.maps.InfoWindow({
					content: contentString
				});
			
				t.google.maps.event.addListener(marker, 'click', function() {
					infowindow.open(map,marker);
				});
			}
		});
		
		var mapOptions = {
		    zoom: 15,
		    //center: new t.google.maps.LatLng(-34.397, 150.644),
		    mapTypeId: t.google.maps.MapTypeId.ROADMAP
		};
		
		map = new t.google.maps.Map(document.getElementById('em-plugin-maps-canvas'), mapOptions);
	}
};

$.fn.pluginParticipantsEvent = function(options) {

	var isMethodCall = typeof options === "string",
		args = Array.prototype.slice.call( arguments, 1 ),
		returnValue = this;

	// prevent calls to internal methods
	if ( isMethodCall && options.charAt( 0 ) === "_" ) {
		return returnValue;
	}

	if ( isMethodCall ) {
		this.each(function() {
			var instance = $.data( this, 'MapsPlugin' ),
				methodValue = instance && $.isFunction( instance[options] ) ?
					instance[ options ].apply( instance, args ) :
					instance;

			if ( methodValue !== instance && methodValue !== undefined ) {
				returnValue = methodValue;
				return false;
			}
		});
	} else {
		this.each(function() {
			var instance = $.data( this, 'MapsPlugin' );
			if ( !instance ) {
				$.data( this, 'MapsPlugin', new MapsPlugin( this, options ) );
			}
		});
	}

	return returnValue;
};

// Association en tant que plugin jQuery
//$.fn.MapsPlugin = plugin.MapsPlugin;

// Si l'eventManager a été déclaré on le surcharge pour la gestion du plugin
if(typeof $.eventManager != 'undefined'){
	var em = $.eventManager;
	
	// Ajout du plugin au register du manager, il sera instancié par le manager automatiquement
	em.addPluginToRegister('MapsPlugin', MapsPlugin);
	
	// Ajout d'une fonction lors du callback du init plugins
	em.addCallBackInit(function(){
	});
}

})(jQuery);